<?php

namespace App\Http\Controllers;

use App\Http\Requests\SchoolCreate;
use App\Models\Campus;
use App\Models\School;
use App\Models\SchoolUser;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SchoolController extends BaseController
{
    use ValidatesRequests;

    public function list()
    {

        $res = School::whereHas('schoolUsers', function ($su) {
            $su->where('user_id', Auth::id());
        })->get([
            'id as school_id',
            'school_name'
        ]);
        return resSucc($res, "学校列表");
    }

    public function create(SchoolCreate $request)
    {

        $requestData = $request->validated();

        DB::beginTransaction();

        try {

            // 创建学校
            $school = new School;
            $school->school_name = $requestData["school_name"];
            $school->logo = $requestData["logo"];
            $school->save();

            // 创建校区
            $campus = new Campus;
            $campus->campus_name = $requestData["campus_name"];
            $campus->school_id = $school->id;
            $campus->save();

            // 创建管理员
            $authUser = Auth::user();
            $schoolUser = new SchoolUser;
            $schoolUser['school_id'] = $school->id;
            $schoolUser['campus_id'] = $campus->id;
            $schoolUser['user_id'] = $authUser->id;
            $schoolUser['teacher_name'] = $authUser->nickname;
            $schoolUser['sex'] = "3";
            $schoolUser['phone'] = $authUser->passport;
            $schoolUser['entry_at'] = time();
            $schoolUser['identity'] = "school";
            $schoolUser->save();

            DB::commit();
            return resSucc(true, "创建成功");
        } catch (\Exception $e) {
            DB::rollback();
            return resFail($e, "创建失败");
        } catch (\Throwable $e) {
            DB::rollback();
            return resFail($e, "创建失败");
        }
    }
}
